﻿using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Twitt.Common;

namespace Twitt.Views
{
    public partial class DetailPage
    {
        private DetailPageData _detailItem;
        public DetailPage()
        {
            InitializeComponent();
            CreateApplicationBar();
            Loaded += Post_Loaded;
        }

        #region ApplicationBar

        private void CreateApplicationBar()
        {
            ApplicationBar = new ApplicationBar { IsMenuEnabled = true, IsVisible = true, Opacity = .9 };

            var favorite = new ApplicationBarIconButton(new Uri("/Resources/Images/favorite.png", UriKind.Relative));
            favorite.Text = "favorite";
            favorite.Click += FavoriteClick;
            ApplicationBar.Buttons.Add(favorite);

            var sendEmail = new ApplicationBarIconButton(new Uri("/Resources/Images/mail.png", UriKind.Relative));
            sendEmail.Text = "E-mail tweet";
            sendEmail.Click += SendMailClick;
            ApplicationBar.Buttons.Add(sendEmail);

            var retweet = new ApplicationBarIconButton(new Uri("/Resources/Images/retweet.png", UriKind.Relative));
            retweet.Text = "retweet";
            retweet.Click += RetweetClick;
            ApplicationBar.Buttons.Add(retweet);

            var reply = new ApplicationBarIconButton(new Uri("/Resources/Images/reply.png", UriKind.Relative));
            reply.Text = "reply";
            reply.Click += ReplyClick;
            ApplicationBar.Buttons.Add(reply);

            var tweet = new ApplicationBarMenuItem("Send direct message");
            tweet.Click += SendDirectMessageClick;
            ApplicationBar.MenuItems.Add(tweet);

            var browserItem = new ApplicationBarMenuItem("Open in Internet Explorer");
            browserItem.Click += OpenInBrowserItemClick;
            browserItem.IsEnabled = false;
            ApplicationBar.MenuItems.Add(browserItem);
        }

        private void SendMailClick(object sender, EventArgs e)
        {
            var task = new EmailComposeTask
                            {
                                Body = _detailItem.Text, 
                                Subject = String.Format("Tweet by {0}", _detailItem.UserDisplayName)
                            };
            task.Show();
        }

        private void SendDirectMessageClick(object sender, EventArgs e)
        {
            var tweetPage = new TweetPageData
            {
                Tweet = String.Format("d {0} ", _detailItem.UserName),
            };

            Helper.SaveSetting(Constants.TweetPageFileName, tweetPage);

            NavigationService.Navigate(new Uri("/Views/TweetPage.xaml", UriKind.Relative));
        }

        private void OpenInBrowserItemClick(object sender, EventArgs e)
        {
            var task = new WebBrowserTask { URL = WebBrowser.Source.ToString() };
            task.Show();
        }

        private void FavoriteClick(object sender, EventArgs e)
        {
            ProgressBar.IsIndeterminate = true;
            ProgressBar.Visibility = Visibility.Visible;

            var twitter = new TwitterHelper();
            twitter.FavoriteCompletedEvent += (sender2, e2) =>
            {
                ProgressBar.IsIndeterminate = false;
                ProgressBar.Visibility = Visibility.Collapsed;
                MessageBox.Show("Item added to favorites");
            };
            twitter.ErrorEvent += (sender2, e2) =>
            {
                ProgressBar.IsIndeterminate = false;
                ProgressBar.Visibility = Visibility.Collapsed;
            };
            twitter.FavoriteItem(_detailItem.Id);
        }

        private void RetweetClick(object sender, EventArgs e)
        {
            var tweetPage = new TweetPageData
            {
                Tweet = String.Format("RT @{0} {1}", _detailItem.UserName, _detailItem.Text)
            };

            // Save the detailpage object which the detailpage will load up
            Helper.SaveSetting(Constants.TweetPageFileName, tweetPage);

            NavigationService.Navigate(new Uri("/Views/TweetPage.xaml", UriKind.Relative));
        }

        private void ReplyClick(object sender, EventArgs e)
        {
            var tweetPage = new TweetPageData
            {
                Tweet = String.Format("@{0} ", _detailItem.UserName)
            };

            // Save the detailpage object which the detailpage will load up
            Helper.SaveSetting(Constants.TweetPageFileName, tweetPage);

            NavigationService.Navigate(new Uri("/Views/TweetPage.xaml", UriKind.Relative));
        }

        #endregion

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _detailItem = Helper.LoadSetting<DetailPageData>(Constants.DetailPageFileName);
            if (_detailItem == null)
            {
                MessageBox.Show("Error loading page data");
                return;
            }

            PageTitle.Text = _detailItem.UserDisplayName;
        }

        private void Post_Loaded(object sender, RoutedEventArgs e)
        {
            var html = new StringBuilder();

            html.Append(String.Format("{0}<br><br>", _detailItem.CreatedDate));
            html.Append(MakeLinks(_detailItem.Text));
            if (!String.IsNullOrEmpty(_detailItem.Source))
                html.Append(String.Format("<br><br>Source: {0}", _detailItem.Source));

            WebBrowser.NavigateToString(html.ToString());
        }

        private static string MakeLinks(string txt)
        {
            var regx = new Regex(@"http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&amp;\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase);
            var mactches = regx.Matches(txt);

            return mactches.Cast<Match>().Aggregate(txt, (current, match) => current.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>"));
        }

        private void WebBrowserNavigating(object sender, NavigatingEventArgs e)
        {
            ProgressBar.Visibility = Visibility.Visible;
            ProgressBar.IsIndeterminate = true;

            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;
        }

        private void WebBrowserNavigated(object sender, NavigationEventArgs e)
        {
            ProgressBar.Visibility = Visibility.Collapsed;
            ProgressBar.IsIndeterminate = false;
        }

    }
}